package com.jc.order.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jc.constant.PolicyAttachmentTypeConst;
import com.jc.order.common.DictionaryToJcConst;
import com.jc.order.constant.ErrorCode;
import com.jc.order.constant.OrderConst;
import com.jc.order.domain.CustomerApiSecret;
import com.jc.order.dto.*;
import com.jc.order.service.ApiBaseService;
import com.jc.order.service.CustomerApiSecretService;
import com.jc.order.service.SystemTenantService;
import com.jc.util.Result;
import com.jc.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class ApiBaseServiceImpl implements ApiBaseService {

    @Autowired
    private CustomerApiSecretService customerApiSecretService;
    @Autowired
    private SystemTenantService systemTenantService;


    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public SystemTenantDTO getTenantById(Long id, Result result) {
        SystemTenantDTO tenant = systemTenantService.queryById(id);
        if (tenant == null) {
            result.error(ErrorCode.BASE_INFO_ERROR, "客户未找到");
        } else {
            result.ok();
        }
        return tenant;
    }

    @Override
    public SystemTenantDTO validateBaseInfo(OrderRequest request, Result result) {
        CustomerApiSecret secret = customerApiSecretService.queryBySecretId(request.getSecretId());
        if (secret == null) {
            result.error(ErrorCode.BASE_INFO_ERROR, "无效的密钥ID");
            return null;
        }
        SystemTenantDTO tenant = this.getTenantById(secret.getCustomerId(),result);
        return tenant;
    }

    @Override
    public PolicyRequest parseRequestData(String jsonData, Result result) {
        try {
            return objectMapper.readValue(jsonData, PolicyRequest.class);
        } catch (JsonProcessingException e) {
            log.error("请求数据解析失败: {}", jsonData, e);
            result.error(ErrorCode.DATA_PARSE_ERROR, "数据格式错误");
            return null;
        }
    }


    @Override
    public JcPolicyDTO buildBaseInsuranceData(PolicyRequest policyRequest, SystemTenantDTO tenant) {
        JcPolicyDTO dto = new JcPolicyDTO();

        this.buildBaseInsuranceData(tenant, dto);
        // 被保险人信息
        setInsuredInfo(dto, policyRequest);

        // 设置业务字段
        setBusinessFields(policyRequest, dto);
        // 附件
        processAttachments(policyRequest, dto);

        return dto;
    }

    @Override
    public void buildBaseInsuranceData(SystemTenantDTO tenant, JcPolicyDTO dto) {

        Date now = new Date();
        // 初始化基础字段
        initBaseFields(dto, now);
        // 投保人信息
        setPolicyholderInfo(dto, tenant);

    }


    // 构建Response
    @Override
    public PolicyResponseVO buildResponseVO(PolicyRequest policyRequest, JcPolicyDTO dto) {
        PolicyResponseVO vo = new PolicyResponseVO();
        BeanUtils.copyProperties(policyRequest, vo);
        vo.setSumInsured(dto.getInsuranceAmount());
        vo.setExchangeRate(dto.getExchangeRate());
        vo.setStatus(dto.getStatus());
        vo.setUniqueCode(dto.getSnNo());
        vo.setFeeRate(dto.getFeeRate());
//        vo.setPremium(dto.getFee());
        vo.setPremium(dto.getPremium());
        vo.setRmbPremium(dto.getRmbPremium());
        vo.setRmbSumInsured(dto.getRmbSumInsured());
        vo.setRmbPremiumBeforeDiscount(dto.getRmbPremiumBeforeDiscount());
        return vo;
    }

    @Override
    public PolicyVO buildResponseVO(JcPolicyDTO dto) {
        PolicyVO vo = new PolicyVO();
        BeanUtils.copyProperties(dto, vo);
        PolicyResponse response = new PolicyResponse();
        response.setSnNo(dto.getSnNo());
        response.setInsuranceSn(dto.getInsuranceSn());
        response.setInsuranceFile(dto.getInsuranceFile());
//        response.setStatus(dto.getStatus());
        response.setExchangeRate(dto.getExchangeRate());
        response.setFeeRate(dto.getFeeRate());
//        response.setFee(dto.getFee());
        response.setFee(dto.getPremium());
        response.setRmbPremium(dto.getRmbPremium());
        response.setRmbSumInsured(dto.getRmbSumInsured());
        response.setPremiumBeforeDiscount(dto.getRmbPremiumBeforeDiscount());
        response.setInsuranceAmount(dto.getInsuranceAmount());

        if (!NumberUtil.equals(dto.getOriginalFee(),dto.getFee())){
            response.setOriginalFee(dto.getOriginalFee());
            response.setOriginalFeeRate(dto.getOriginalFeeRate());
        }

        vo.setResponse(response);
        return vo;
    }


    // 初始化基础字段
    private void initBaseFields(JcPolicyDTO dto, Date now) {

        dto.setUserId(OrderConst.DEFAULT_USER_ID);
        dto.setBatchId(OrderConst.DEFAULT_BATCH_ID);
        dto.setStatus(OrderConst.STATUS_20);
        dto.setCreateTime(now);
        dto.setUpdateTime(now);
        dto.setDeleted(Boolean.FALSE);
        if (StrUtil.isEmpty(dto.getCompensationLocation())) {
            dto.setCompensationLocation("NINGBO CHINA");
        }
        //暴动
        Boolean riotProtection = dto.getRiotProtection();
        if (riotProtection == null) {
            dto.setRiotProtection(false);
        }

        if (OrderConst.PRODUCT_CODE_1.equalsIgnoreCase(dto.getProductCode())) {
            Boolean b = dto.getWarehouseTermsRequired();
            if (b == null) {
                dto.setWarehouseTermsRequired(false);
            }
            Byte startTimeDisplayMode = dto.getStartTimeDisplayMode();
            if (startTimeDisplayMode == null) {
                //同起运日
                dto.setStartTimeDisplayMode(new Byte("1"));
            }
        } else if (OrderConst.PRODUCT_CODE_2.equalsIgnoreCase(dto.getProductCode())) {
            dto.setLostCareOnly(dto.getLostCareOnly() == null ? false : dto.getLostCareOnly()); //保丢不保损
            dto.setWarProtection(dto.getWarProtection() == null ? false : dto.getWarProtection()); //战争险保障
            dto.setIncorrectDispatchProtection(dto.getIncorrectDispatchProtection() == null ? false : dto.getIncorrectDispatchProtection());//送错地址保障
            dto.setReturnProtection(dto.getReturnProtection() == null ? false : dto.getReturnProtection());  //回邮附加责任
        }

    }


    // 设置业务字段
    private void setBusinessFields(PolicyRequest request, JcPolicyDTO dto) {
        if (request == null) {
            return;
        }

        dto.setFromCountry(request.getDepartureCountryCode());
        dto.setTransferCountry(request.getTransferCountryCode());
        dto.setToCountry(request.getDestinationCountryCode());
        dto.setFromAddress(request.getDepartureAddress());
        dto.setTransferAddress(request.getTransferAddress());
        dto.setToAddress(request.getDestinationAddress());

        dto.setOrderNumber(request.getTrackingNo());
        dto.setTransportName(request.getTransportTool());
        dto.setWaybillNumber(request.getBlNo());

        dto.setStartTime(request.getDepartureDate());
        dto.setGoodsNote(request.getCargoDesc());
        dto.setPackageCount(request.getPackingQuantity());
        dto.setWeightPackaged(request.getChargeableWeight());

        dto.setCurrency(request.getCurrencyCode());
        dto.setGoodsValueAmount(request.getCargoValue());
        dto.setAppendPercent(request.getRatio());
        dto.setCreator(request.getCreateUserName());

        dto.setInsuranceConfirmType(DictionaryToJcConst.INSURANCECONFIRMTYPE_MAP.get(request.getBaseAmountWay()));

        // 使用 Optional 处理布尔值
        dto.setRiotProtection(Optional.ofNullable(request.getUnrestRisk()).orElse(false));

    }

    // 处理附件
    private void processAttachments(PolicyRequest request, JcPolicyDTO dto) {
        if (request == null) {
            return;
        }
        Optional.ofNullable(request.getAttachmentList()).orElse(Collections.emptyList()).stream()
                .filter(attachment -> attachment != null && StrUtil.isNotBlank(attachment.getType()))
                .forEach(attachment -> {
                    String type = attachment.getType().toLowerCase();
                    if (PolicyAttachmentTypeConst.INSURE_ATTACHED_FILE_CARGO_DESC.equalsIgnoreCase(type)) {
                        dto.setGoodsNoteFile(attachment.getUrl());
                    }
                });
    }


    /**
     * 设置投保人信息
     */
    private void setPolicyholderInfo(JcPolicyDTO dto, SystemTenantDTO tenant) {
        dto.setPolicyholder(tenant.getName());
        dto.setPolicyholderType(OrderConst.CORPORATE_TYPE);
        dto.setPolicyholderContact(tenant.getContactName());
        dto.setPolicyholderPhone(tenant.getContactMobile());
        dto.setTenantId(tenant.getId());
        dto.setVersionType(tenant.getVersionType());
        dto.setFeeVersionType(tenant.getFeeVersionType());
    }

    /**
     * 设置被保险人信息
     */
    private void setInsuredInfo(JcPolicyDTO dto, PolicyRequest request) {

        if (request == null) {
            return;
        }
        PolicyInsured insured = request.getInsuredInfo();
        dto.setInsured(request.getInsuredName());
        dto.setInsuredType("101".equalsIgnoreCase(insured.getCertificateType()) ? OrderConst.CORPORATE_TYPE : OrderConst.INDIVIDUAL_TYPE);
        dto.setInsuredId(insured.getCertificateNo());
        dto.setInsuredPhone(insured.getMobile());
        dto.setInsuredAddress(insured.getContactAddress());
    }

}
